package com.dq.interceptors;

import com.dq.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取请求的URL
        String requestUrl = request.getRequestURL().toString();

        String sessionId = (String) request.getSession().getAttribute("admin");
        Integer id = -1;
        
        if(sessionId != null){
            id = Integer.parseInt(sessionId);
        }
        
        log.info("拦截到请求: {}, 用户id: {}", requestUrl, id);

        if(requestUrl.endsWith("/index.html")) {
            return true;
        }

        if(requestUrl.endsWith("/admin/login")) {
            return true;
        }

        if(requestUrl.contains("/captcha/generate")) {
            return true;
        }

        if(id == null || id == -1){
            log.info("用户未登录，转向");

            response.sendRedirect("/index.html");

            return false;
        }

        log.info("用户已登录，放行");

        BaseContext.setCurrentId(Long.valueOf(id));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        BaseContext.setCurrentId(null);

    }
}
